package com.gopay.checkorder.service.task;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.util.DateUtils;
import com.gopay.common.util.FtpUtil;
import com.gopay.common.util.SendMail;

/**
 * 民生代扣下载对账文件
 * 
 * @CmbcExPayDownloadOrderTaskImpl.java
 * @author jiangxiangjiao
 */
@SuppressWarnings("all")
public class IPayExPayDownloadOrderTaskImpl implements Task {
    private final static Logger logger = LoggerFactory.getLogger("CHECK_ORDER");
    
    @Resource(name = "ipayexpayConfig")
    private Map<String, String> ipayexpayConfig;
    
    private final String companyId = "KJ_GFB";

    private int port = 21;

    @Override
    public void doTask() {
    	logger.error("IPayExPayDownloadOrderTaskImpl: 定时任务start ");
        try {
            if ("off".equals(ipayexpayConfig.get("mailSwitch"))) {
                logger.error("IPayExPayDownloadOrderTaskImpl: 不进行ftp操作直接返回!");
                return;
            }

            String url = ipayexpayConfig.get("ftp.url");
            String username = ipayexpayConfig.get("ftp.username");
            String password = ipayexpayConfig.get("ftp.password");
            String locpath = ipayexpayConfig.get("ftp.locpath");
            String FTime = DateUtils.getYesterday();
            String FPath = FTime;
            String payFileName = companyId + "_IPAYZFDZ_" + FTime + ".txt";//支付文件名称
            String refundFileName = companyId + "_IPAYTKDZ_" + FTime + ".txt";//退款文件名称
            String encoding = "UTF-8";
            List sendFile = new ArrayList();//发送文件列表
            List names = new ArrayList();
            
            List payNames = new ArrayList();//支付文件名称列表
            List refundNames = new ArrayList();//退款文件名称列表
            String messageText = "";//邮件正文

            FtpUtil ftpUtil = new FtpUtil();
            
            // 目录不存在则创建目录
            File dir = new File(locpath);
            if(!dir.exists()){
            	dir.mkdirs();
            }
            // 判断本地服务器是否存在i支付快捷支付对账文件
            if (!(new File(locpath + payFileName).exists())) {
                // 判断i支付快捷支付对账文件是否存在
                if (ftpUtil.exist(url, port, username, password, FPath, payFileName, encoding)) {
                    logger.error("IPayExPayDownloadOrderTaskImpl " + payFileName + "exist!");
                    // 下载i支付快捷支付对账文件
                    if (FtpUtil.downFile(url, port, username, password, FPath, payFileName, locpath, payFileName, encoding)) {
                        logger.error("IPayExPayDownloadOrderTaskImpl " + payFileName + " downLoad success!");
                        payNames.add(payFileName);
                    }
                    names.addAll(payNames);
                }
            } else {
                logger.error("IPayExPayDownloadOrderTaskImpl local " + payFileName + " 支付对账文件已成功下载, 不再进行ftp操作!");
            }
            // 判断本地服务器是否存在i支付快捷退款对账文件
            if (!(new File(locpath + refundFileName).exists())) {
                // 判断i支付快捷退款对账文件是否存在
                if (ftpUtil.exist(url, port, username, password, FPath, refundFileName, encoding)) {
                    logger.error("IPayExPayDownloadOrderTaskImpl " + refundFileName + "exist!");
                    // 下载i支付快捷退款对账文件
                    if (FtpUtil.downFile(url, port, username, password, FPath, refundFileName, locpath, refundFileName, encoding)) {
                        logger.error("IPayExPayDownloadOrderTaskImpl " + refundFileName + " downLoad success!");
                        refundNames.add(refundFileName);
                    }
                    names.addAll(refundNames);
                }
            } else {
                logger.error("IPayExPayDownloadOrderTaskImpl local " + refundFileName + " 退款对账文件已成功下载, 不再进行ftp操作!");
            }
            
            // 若文件以########开头，则代表内容为空
            for (Iterator it = names.iterator(); it.hasNext();) {
                String localPath = locpath + (String) it.next();
                String fileText = readFile(localPath);
                if (fileText.startsWith("########")) {
                    logger.error("IPayExPayDownloadOrderTaskImpl " + localPath + "is null");
                    it.remove();
                }
            }
            
            // 若对账文件全部为空，则邮件内容标明
            if (names.size() < 1) {
                logger.error("IPayExPayDownloadOrderTaskImpl: 民生i支付快捷对账文件为null或本地已成功下载!");
                return;
            } else {
            	if(payNames.size() < 1){
            		messageText += FTime + ": 民生i支付快捷退款对账文件见附件!" + payFileName + ";";
            	}
            	if(refundNames.size() < 1){
            		messageText += FTime + ": 民生i支付快捷退款对账文件见附件!" + refundFileName + ";";
            	}
                for (int i = 0; i < names.size(); i++) {
                    sendFile.add(locpath + (String) names.get(i));
                }
            }
            String subject = "民生i支付快捷对账文件";
            String[] cc = ipayexpayConfig.get("sendmail.cc").split(","); // 获取多个抄送人
            List ccList = Arrays.asList(cc);

            SendMail.sendMessage(ipayexpayConfig.get("sendmail.host"), ipayexpayConfig.get("sendmail.sender"),
                    ipayexpayConfig.get("sendmail.username"), ipayexpayConfig.get("sendmail.password"),
                    ipayexpayConfig.get("sendmail.receiver"), subject, messageText, "text/html;charset=gb2312", ccList,
                    sendFile, names);
        } catch (Exception e) {
            logger.error("IPayExPayDownloadOrderTaskImpl error: ", e);
        }
    }
    
    /**
     * 获取文件内容
     * 
     * @param path
     * @return
     * @throws IOException
     */
    private String readFile(String path) throws IOException {
        FileReader fr = new FileReader(path);
        BufferedReader br = new BufferedReader(fr);
        StringBuffer sb = new StringBuffer();
        while (br.ready()) {
            sb.append(br.readLine());
        }
        if (null != fr) {
            fr.close();
        }
        if (null != br) {
            br.close();
        }
        return sb.toString();
    }
}
